const db = require('../db/index')
    //引入加密包
const bcrypt = require('bcryptjs')
exports.getUsers = (req, res) => {
        //接收数据，get 请求数据 如果是post请求 req.body
        // console.log(req.query);
        //获取关键字
        const keyword = req.query.query;
        const page_size = req.query.pagesize; //每页显示的条数
        const page_num = req.query.pagenum; //当前的页码数
        if (page_size == '' || page_num == '') {
            res.ResData("参数错误")
        }
        // var sql = "select * from sp_manager,sp_role where sp_manager.role_id=sp_role.role_id limit ?,?"
        var sql = "select * from sp_manager left join sp_role on sp_manager.role_id=sp_role.role_id "
        if (keyword) {
            sql += "where sp_manager.mg_name like '%" + keyword + "%'limit ?,?"
        } else {
            sql += "limit ?,?"
        }
        var params = [(parseInt(page_num) - 1) * parseInt(page_size), parseInt(page_size)]
            // console.log(params);
        db.query(sql, params, (err, result) => {
            if (err) return res.ResData("查询失败!", err)
                // res.ResData("获取用户列表成功", 200, result)
                //计算总记录数
            var sqlTotal = "select count(*) as num from sp_manager "
            if (keyword) {
                sqlTotal += "where mg_name like '%" + keyword + "%'";
            }
            db.query(sqlTotal, (err, among) => {
                if (err) return res.ResData(err)
                var total = among[0]['num'] //总记录数
                if (page_num > Math.ceil(total / page_size)) {
                    return res.ResData("已经超过最大页")
                }
                // res.ResData("获取用户列表成功", 200, result)
                //组合返回数据
                var retUsers = []
                for (idx in result) {
                    var manager = result[idx];
                    var role_name = manager.role_name
                    if (!manager.role_id) {
                        role_name = "炒鸡管理员"
                    }
                    retUsers.push({
                        'id': manager.mg_id,
                        'username': manager.mg_name,
                        'mobile': manager.mg_mobile,
                        'email': manager.mg_email,
                        'create_time': manager.mg_time,
                        'mg_state': manager.mg_state == 1,
                        'role_name': role_name
                    })
                }
                const data = {
                    "totalpage": total,
                    "pagenum": page_num,
                    "users": retUsers,
                }
                res.ResData("获取用户列表成功", 200, data)
            })
        })

    }
    //添加用户
exports.addUsers = (req, res) => {
        // res.ResData("添加用户")
        //1.获取数据
        // console.log(req.body);
        var mg_name = req.body.username
            //头部引入加密包
        var mg_pwd = bcrypt.hashSync(req.body.password)
        var mg_email = req.body.email
        var mg_mobile = req.body.mobile
        var mg_time = (Date.parse(new Date()) / 1000)
            //2.检查用户名是否存在
        var sql = "select * from sp_manager where mg_name=?"
        db.query(sql, mg_name, (err, result) => {
                if (err) return res.ResData("添加失败!")
                if (result.length > 0) return res.ResData("用户名已存在!")
                    //3.添加数据
                var sql = "insert into sp_manager (mg_name,mg_pwd,mg_time,mg_mobile,mg_email,mg_state)values(?,?,?,?,?,?)"
                db.query(sql, [mg_name, mg_pwd, mg_time, mg_mobile, mg_email, 0], (err, data) => {
                    if (err) return res.ResData("添加失败!")
                    res.ResData("添加用户成功", 200, {
                        "username": mg_name,
                        "mobile": mg_mobile,
                        "email": mg_email,
                        "create_time": mg_time
                    })
                })
            })
            //4.返回结果


        // if (!req.body.username) {
        //     return res.ResData(null, 400, "用户名不能为空");
        // }
        // if (!req.body.password) {
        //     return res.ResData(null, 400, "密码不能为空");
        // }
        // if (!req.body.rid) {
        //     req.body.rid = -1;
        //     //return res.sendResult(null,200,"角色ID不能为空");
        // }
        // if (isNaN(parseInt(req.body.rid))) req.body.rid = -1; //return res.sendResult(null,200,"角色ID必须是数字");
        // next();

    }
    //修改用户状态
exports.changeState = (req, res) => {
        // res.ResData("修改用户状态")
        // console.log(req.body);
        //获取用户数据
        // var mg_name = req.body.username
        // var mg_email = req.body.email
        // var mg_mobile = req.body.mobile

        var id = req.params.uId
        var mg_state = req.params.type
        if (mg_state === 'true') mg_state = 1
        else mg_state = 0
            //更新状态
        var sql = "update sp_manager set `mg_state`=? where `mg_id`=?"
        db.query(sql, [mg_state, id], (err, result) => {
            if (err) return res.ResData("修改用户状态失败!", err)
            res.ResData("更新状态成功", 200, {
                "id": id,
                // "username": mg_name,
                // "mobile": mg_mobile,
                // "email": mg_email,
                "mg_state": mg_state
            })
        })
    }
    //根据 ID 查询用户信息
exports.searchUsers = (req, res) => {
    // res.ResData("查询用户信息")
    // 1接受参数
    var id = req.params.id;
    // 2.查询用户信息
    var sql = "select * from sp_manager where mg_id=?"
    db.query(sql, id, (err, result) => {
        if (err) return res.ResData("用户查询失败")
            // 3.返回结果
        if (result.length > 0) {
            res.ResData("用户查询成功", 200, {
                "id": result[0].mg_id,
                "username": result[0].mg_name,
                "role_id": result[0].role_id,
                "mobile": result[0].mg_mobile,
                "email": result[0].mg_email
            })
        } else {
            res.ResData("用户查询失败")
        }

    })
}
exports.editUsers = (req, res) => {
    // res.ResData("编辑数据")
    // 1.接收数据
    var id = req.params.id;
    var mobile = req.body.mobile;
    var email = req.body.email;
    // 2.更新数据
    var sql = "update sp_manager set mg_mobile=?,mg_email=? where mg_id=?";
    db.query(sql, [mobile, email, id], (err, result) => {
        if (err) return res.ResData("更新用户信息失败")
            // console.log(result);
        if (result.affectedRows < 1)
            return res.ResData("更新失败")
        var sql = "select * from sp_manager where mg_id=?"
        db.query(sql, id, (err, resResult) => {
            res.ResData("更新信息成功", 200, {
                    "id": resResult[0].mg_id,
                    "username": resResult[0].mg_name,
                    "role_id": resResult[0].role_id,
                    "mobile": resResult[0].mg_mobile,
                    "email": resResult[0].mg_email
                })
                // console.log(resResult);
        })
    })

}
exports.deleteUsers = (req, res) => {
    // res.ResData("删除")
    var id = req.params.id;
    var sql = "delete from sp_manager where mg_id=?"
    db.query(sql, id, (err, result) => {
        if (err) return res.ResData("删除失败")
        if (result.affectedRows != 1) return res.ResData("删除失败")
        res.ResData("删除成功", 200)
    })
}
exports.distributeUsers = (req, res) => {
    // res.ResData("分配")
    var id = req.params.id;
    var rid = req.body.rid;
    var sql = "update sp_manager set role_id=? where mg_id=?"
    db.query(sql, [rid, id], (err, result) => {
        if (err) return res.ResData("设置角色失败");
        if (result.affectedRows != 1) return res.ResData("设置角色失败");
        var sql = "select * from sp_manager where mg_id=?"
        db.query(sql, id, (err, data) => {
            res.ResData("设置角色成功", 200, {
                "id": data[0].mg_id,
                "username": data[0].mg_name,
                "role_id": data[0].role_id,
                "mobile": data[0].mg_mobile,
                "email": data[0].mg_email
            })
        })

    })
}